package com.woniuxy.health.manager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.health.aspect.ManagerThreadLocalData;
import com.woniuxy.health.aspect.OperationLogAnnotation;
import com.woniuxy.health.manager.dto.AccountDto;
import com.woniuxy.health.manager.dto.ManagerDto;
import com.woniuxy.health.manager.vo.ManagerVo;
import com.woniuxy.health.manager.vo.PageVo;
import com.woniuxy.health.model.manager.Manager;
import com.woniuxy.health.model.manager.Role;
import com.woniuxy.health.utils.TokenUtil;
import com.woniuxy.health.manager.vo.TokenVo;
import com.woniuxy.utils.result.Asserts;
import com.woniuxy.utils.result.Result;
import com.woniuxy.utils.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.woniuxy.health.manager.service.IManagerService;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author woniuxy
 * @since 2023-09-04
 */
@RestController
@RequestMapping("/manager")
@CrossOrigin
public class ManagerController {

    private final IManagerService managerServiceImpl;

    @Autowired
    public ManagerController(IManagerService managerServiceImpl) {
        this.managerServiceImpl = managerServiceImpl;
    }

    @Value("${jwt.signature}")
    private String signature;
    @Value("${jwt.accessTime}")
    private Integer accessTime;
    @Value("${jwt.refreshTime}")
    private Integer refreshTime;

    @OperationLogAnnotation(module = "账号管理-管理员登录", type = "登录", description = "管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody ManagerDto managerDto, HttpServletRequest request) {
        //查询数据库，判断是否存在管理员账号，如果不存在，则抛出：用户名或密码错误的异常！
        Manager manager = managerServiceImpl.login(managerDto);
        Asserts.fail(Objects.isNull(manager), ResultCodeEnum.ACCOUNT_PWD_ERROR);
        //长短令牌都生成成功
        String accessToken = TokenUtil.createAccessToken(accessTime, manager, signature, request);
        String refreshToken = TokenUtil.createRefreshToken(refreshTime, manager, signature, request);
        if (manager.getState() == 1) {
            // 登录成功后将account和nickName存储在会话中
//            request.getSession().setAttribute("account", manager.getAccount());
//            request.getSession().setAttribute("nickName", manager.getNickName());
            ManagerThreadLocalData.set("account", manager.getAccount());
            ManagerThreadLocalData.set("nickName", manager.getNickName());

            return Result.ok(new TokenVo(accessToken, refreshToken, manager.getId(), manager.getAccount(), manager.getNickName()));
        } else {
            return Result.build(null, ResultCodeEnum.ACCOUNT_DISABLED);
        }
    }

    @PostMapping("/findAllPage/{pageSize}/{pageNum}")
    public Result findAllPage(@PathVariable("pageSize") Integer pageSize, @PathVariable("pageNum") Integer pageNum, @RequestBody AccountDto accountDto) {
        Page<Manager> page = Page.of(pageNum, pageSize);
        PageVo<ManagerVo> vo = managerServiceImpl.findAllPage(page, accountDto);
        return Result.ok(vo);
    }

    @GetMapping("/findByAccount")
    public Result findByAccount(String managerInfo) {
        Manager manager = managerServiceImpl.findByAccount(managerInfo);
        if (manager != null) {
            return Result.ok(manager);
        }
        return Result.fail();
    }

    @GetMapping("/findByNickName")
    public Result findByNickName(String managerInfo) {
        Manager manager = managerServiceImpl.findByNickName(managerInfo);
        if (manager != null) {
            return Result.ok(manager);
        }
        return Result.fail();
    }

    @GetMapping("/authentication")
    public Result authentication(String account, String password) {
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account)
                .eq("password", password);
        Manager manager = managerServiceImpl.getOne(queryWrapper);
        if (manager != null) {
            // 身份验证成功，返回用户信息
            return Result.ok(ResultCodeEnum.SUCCESS);
        } else {
            // 身份验证失败
            return Result.fail(ResultCodeEnum.PWD_ERROR);
        }
    }

    @OperationLogAnnotation(module = "账号管理-管理员账号新增", type = "新增", description = "新增管理员账号")
    @PostMapping("/add")
    public Result addManager(@RequestBody Manager manager) {
        manager.setPassword("123456");
        managerServiceImpl.save(manager);
        return Result.ok();
    }

    @OperationLogAnnotation(module = "账号管理-管理员账号信息更新", type = "更新", description = "更新管理员账号")
    @PostMapping("/update")
    public Result updateManager(@RequestBody Manager manager) {
        managerServiceImpl.updateById(manager);
        return Result.ok();
    }

    @OperationLogAnnotation(module = "账号管理-管理员账号删除", type = "删除", description = "删除管理员账号")
    @DeleteMapping("/delete/{id}")
    public Result deleteManager(@PathVariable Long id) {
        managerServiceImpl.deleteManager(id);
        return Result.ok();
    }

    @OperationLogAnnotation(module = "账号管理-管理员账号删除", type = "批量删除", description = "批量删除管理员账号")
    @DeleteMapping("/deleteByIds")
    public Result deleteByIds(@RequestBody List<Long> ids) {
        managerServiceImpl.removeBatchByIds(ids);
        return Result.ok();
    }

}
